<template>
  <div>
    <div class="head">
      绑定微信
    </div>
    <vue-wxlogin :loading="loading"
      :href="wx.href"
      :state="wx.state"
      :appid="wx.appid"
      :scope="wx.scope"
      self_redirect="true"
      :redirect_uri="wx.redirect_uri"
      @refresh="refresh"
      height="160px" />
    <p class="text-muted mt10 text-center"
      style="margin-bottom:25px;">绑定微信快捷登录</p>
  </div>
</template>

<script type="text/javascript">
import vueWxlogin from '@/components/vue-wxlogin.vue'
import { getPartyParam } from '@/api/login'
import mixins from './bind-mixins'
export default {
  name: 'BindWx',
  mixins: [mixins],
  components: {
    vueWxlogin
  },
  data () {
    return {
      loading: false,
      wx: {
        href: 'data:text/css;base64,LmltcG93ZXJCb3h7CiAgICBsaW5lLWhlaWdodDogMTsKfQoKLmltcG93ZXJCb3ggLnRpdGxlLAouaW1wb3dlckJveCAuaW5mbywKLnN0YXR1c19pY29uLAouaW1wb3dlckJveCAuc3RhdHVzIHtkaXNwbGF5OiBub25lO30KCi5pbXBvd2VyQm94IC5xcmNvZGUgewogICAgd2lkdGg6IDE2MHB4OwogICAgaGVpZ2h0OiAxNjBweDsKICAgIGJvcmRlcjogMDsKICAgIG1hcmdpbi10b3A6IDA7Cn0=',
        state: 'qekjdsbkje893214wechat',
        appid: '',
        scope: '',
        redirect_uri: encodeURI(`${location.origin}/partylogincb?type=BindWxLoginFinish`),
        style: 'black'
      }
    }
  },
  created () {
    this.getPartyParam()
    window.onBindWxLoginFinish = this.bindWxLoginFinish
  },
  methods: {
    /**
     * 获取第三方登录参数
     */
    getPartyParam () {
      this.loading = true
      getPartyParam({ type: 'wx' }).then(res => {
        const data = res.data || {}
        this.wx.appid = data.appid
        this.wx.scope = data.scope
        this.loading = false
      }).catch(e => {
        this.$PsMessage.closeAll()
        this.loading = false
      })
    },
    /**
     * 刷新二维码
     */
    refresh () {
      this.getPartyParam()
    },
    /**
     * 获取第三方登录成功回调
     */
    bindWxLoginFinish ({ code } = {}) {
      const params = {
        auth_type: 'wx', // phone-绑定手机,wx-绑定微信
        phone: '', // 手机号码,auth_type=phone为必填
        auth_code: code, // 授权码或者手机验证码
        code_id: '', // 手机验证码对应id,只有授权类型为phone需要
        bind_type: 0, // 0-绑定，1-换绑
        old_phone: '',
        old_auth_code: '',
        old_code_id: ''
      }
      this.onBindAuth(params, 'wx').then(() => {
        this.$xz('xz_substat_action', 1741)
      }).catch(() => {
        this.refresh()
      })
    }
  },
  beforeDestroy () {
    window.onBindWxLoginFinish = null
  }
}
</script>

<style lang="scss" scoped>
// @import "@/theme/common/var";
.head {
  margin: -10px 0 20px;
  font-size: 18px;
  font-weight: 400;
  text-align: center;
  color: #fff;
}
</style>
